package demo.java.util.concurrent;

import java.util.Random;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;

import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import demo.java.lang.RunnableDemo;
import demo.java.lang.ThreadDemo;

public class TaskDemo {

    static Random random = new Random();

    private static Logger logger = LoggerFactory.getLogger(TaskDemo.class);

    private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(2), new ThreadFactoryDemo.NamedThreadFactory("Stan"));

    public static void main(String[] args) {
        test2();
        logger.info("over");
    }

    public static void test2() {
        TaskDemo demo = new TaskDemo();
        Future<?> future1 = demo.threadPool.submit(() -> {
            logger.info("hello");
            return;
        });

        Future<?> future2 = demo.threadPool.submit(() -> {
            logger.info("haha");
            return;
        });

        demo.threadPool.shutdown();
    }

    public static void test() {
        TaskDemo demo = new TaskDemo();
        int i = 0;
        while (true) {
            RunnableDemo task = new RunnableDemo(String.valueOf(i++), random.nextInt(300));
            demo.trySubmit(task);
        }
    }

    /**
     * 给线程池提交任务，如果线程池满了拒绝任务，则sleep一段时间后继续提交
     * 
     * @param runnable
     */
    public void submit(RunnableDemo runnable) {
        aa: while (true) {
            try {
                threadPool.submit(runnable);
                break aa;
            } catch (RejectedExecutionException re) {
                logger.error("任务:{}被线程池拒绝,稍后尝试", runnable);
                ThreadDemo.safeSleep(500);
                continue aa;
            }
        }
    }

    public void trySubmit(RunnableDemo runnable) {
        boolean submited = false;
        while (!submited) {
            try {
                threadPool.submit(runnable);
                submited = true;
            } catch (RejectedExecutionException re) {
                logger.error("任务:{}被线程池拒绝,稍后尝试", runnable);
                ThreadDemo.safeSleep(10);
            }
        }
    }
}
